//
//  RateListVC.m
//  ImGuider
//
//  Created by 李陆涛 on 2018/2/28.
//  Copyright © 2018年 imguider. All rights reserved.
//

#import "RateListVC.h"
#import "RateListCell.h"

@interface RateListVC ()

@property (nonatomic, strong) NSArray *charactorArray;
@property (nonatomic, strong) NSDictionary *dataSourceDict;

@end

@implementation RateListVC

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.tableView.rowHeight = 60;
    [self registCells:@[@"RateListCell"]];
    self.tableView.tableFooterView = [UIView new];
    
    self.title = MYLocalizedString(@"EXCHANGE_RATE_CHANGE_CURRENCY", nil);
    
    [self loadDataSource];
}

- (void)loadDataSource {
    
    [ActivityIndicatorView showHUDAddedTo:self.view backgroundColor:[UIColor whiteColor]];
    
    @weakify(self);
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        @strongify(self);
        NSMutableArray *charactorArray = [NSMutableArray array];
        NSMutableDictionary *dataSourceDict = [NSMutableDictionary dictionary];
        
        NSMutableArray *frequentArray = [NSMutableArray array];
        
        NSArray *rateArray = [CountryManager sharedManager].rateArray;
        
        for (RateMode *mode in rateArray) {
            
            NSString *charactor = [IGUtil firstCharactor:mode.smartName];
            
            if (mode.frequent) {
                [frequentArray addObject:mode];
            }
            
            NSMutableArray *dataSource = dataSourceDict[charactor];
            
            if (!dataSource) {
                dataSource = [NSMutableArray array];
                
                [charactorArray addObject:charactor];
                
                [dataSourceDict setObject:dataSource forKey:charactor];
            }
            
            [dataSource addObject:mode];
        }
        
        [dataSourceDict setObject:frequentArray forKey:@"#"];
        
        self.dataSourceDict = dataSourceDict;
        
        NSArray *sortArray = [charactorArray  sortedArrayUsingComparator:^NSComparisonResult(NSString *obj1, NSString *obj2) {
            
            return [obj1 compare:obj2];
        }];

        charactorArray = [NSMutableArray arrayWithArray:sortArray];
        [charactorArray insertObject:@"#" atIndex:0];
        self.charactorArray = charactorArray;
        
        dispatch_async(dispatch_get_main_queue(), ^ {
            [ActivityIndicatorView hideHUDAddedTo:self.view];
            [self.tableView reloadData];
        });
    });
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return self.charactorArray.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    NSString *charactor = self.charactorArray[section];
    
    NSArray *dataSource = self.dataSourceDict[charactor];
    
    return dataSource.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    RateListCell *cell = [tableView dequeueReusableCellWithIdentifier:@"RateListCell" forIndexPath:indexPath];
    
    NSString *charactor = self.charactorArray[indexPath.section];
    
    NSArray *dataSource = self.dataSourceDict[charactor];
    
    cell.mode = dataSource[indexPath.row];
    
    return cell;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    
    static NSString *header = @"customHeader";
    
    UITableViewHeaderFooterView *vHeader;
     
    vHeader = [tableView dequeueReusableHeaderFooterViewWithIdentifier:header];
    
    if (!vHeader) {
        vHeader = [[UITableViewHeaderFooterView alloc] initWithReuseIdentifier:header];
        vHeader.textLabel.backgroundColor = kBGColor;
        
        
        UILabel *textLabel = [UILabel new];
        textLabel.font = Font(12);
        textLabel.textColor = kSubitleColor;
        textLabel.tag = 100;
        
        [vHeader addSubview:textLabel];
        
        [textLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            
            make.left.equalTo(vHeader.mas_left).offset(16);
            make.centerY.equalTo(vHeader.mas_centerY);
        }];
    }
    
    NSString *charactor = self.charactorArray[section];
    
    if ([charactor isEqualToString:@"#"]) {
        charactor = MYLocalizedString(@"EXCHANGE_RATE_COMMON_CURRENCY", nil);
    }
    
    UILabel *textLabel = [vHeader viewWithTag:100];
    
    textLabel.text = charactor;
    
    return vHeader;
}

- (NSArray<NSString *> *)sectionIndexTitlesForTableView:(UITableView *)tableView {
    
    return self.charactorArray;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    NSString *charactor = self.charactorArray[indexPath.section];
    
    NSArray *dataSource = self.dataSourceDict[charactor];
    
    RateMode *selectMode = dataSource[indexPath.row];
    
    NSArray *saveArray = [CountryManager sharedManager].saveRateArray;
    
    if ([saveArray containsObject:selectMode.code]) {
        [IGUtil showToast:MYLocalizedString(@"EXCHANGE_RATE_REUSE", nil)];
        
        return;
    }
    
    NSMutableArray *newArray = [NSMutableArray array];
    
    for (NSString *code in saveArray) {
        
        if ([code isEqualToString:self.selectMode.code]) {
            
            [newArray addObject:selectMode.code];
        } else {
            
            [newArray addObject:code];
        }
    }
    
    [CountryManager sharedManager].saveRateArray = newArray;
    
    if ([_delegate respondsToSelector:@selector(selectedComplete)]) {
        [_delegate selectedComplete];
    }
    [self.navigationController popViewControllerAnimated:YES];
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    
    return 30;
}

@end
